import { Buff, BuffReason } from "@/Battle/Buff/Buff.js";
import { BuffEventType } from "@/Battle/Event/BuffEvent.js";
import { CombatUnitEventType } from "@/Battle/Event/CombatUnitEvent.js";
import { BattleEventType } from "@/Battle/Event/BattleEvent.js";

import CombatEventBus from "@/Battle/CombatEventBus.js";
import { CombatEventPool } from "@/Battle/Event/CombatEventPool.js";

export class SystemBuff extends Buff {
    constructor(id, owner, source) {
        super(id, owner, source);
        this.initFromDB(id);
    }

    initFromDB(id) {
        let state = $dataStates[id];
        if (!state) return;
        if (state.autoRemovalTiming == 1) {//一个角色回合结束
            CombatEventBus.on(
                BattleEventType.Turn.End.Complete,
                this.onDamage
            );
        } else if (state.autoRemovalTiming == 2) {//一轮完毕
            CombatEventBus.on(
                BattleEventType.Round.End.Complete,
                this.onDamage
            );
        }

        if (state.removeByDamage) {
            this.chanceByDamage = state.chanceByDamage / 100;
            this.onDamage = (event) => {
                if (event.payload?.target == this.owner && Math.random() < this.chanceByDamage) {
                    this.requestRemove(
                        this, BuffReason.Remove.damage,
                        this.removeSelf
                    );
                }
            }
            CombatEventBus.on(
                CombatUnitEventType.Damage.Complete,
                this.onDamage
            );
        }
    }

    deattachHandler() {
        CombatEventBus.off(CombatUnitEventType.Damage.Complete, this.onDamage);
    }

    removeSelf = () => {
        this.owner?.forceRmoveBuff(this);
    }

    onRemoved() {
        CombatEventBus.dispatch(
            CombatEventPool.newCombatEvent(
                BuffEventType.Remove.Complete,
                this,
                { source: this.source, target: this.target }
            )
        );
    }

}